#include <app/VirtualClient.h>
#include <msg/forward.h>
#include <router/RouterClient.h>

VirtualClient::VirtualClient(uint32_t server_ip, uint16_t server_port):
    tcp_client(server_ip, server_port),
    App(get_sockfd())
{
    connect();
    running = true;
}

VirtualClient::VirtualClient(std::string_view server_ip, uint16_t server_port):
    tcp_client(server_ip, server_port),
    App(get_sockfd())
{
    connect();
    running = true;
}

void VirtualClient::fd_hander()
{
    char buffer[10240];
    int read_n = read(get_fd(), buffer, sizeof(buffer));
    if (read_n == -1){
        running = false;
        routerctl.notify_virtual_client_disconnect(shared_from_this());
        return;
    }

    forward msg(buffer, read_n);
    send_message_to(msg, get_receiver());
}

void VirtualClient::message_hander(message msg)
{
    if (running == false)
        return;
    if (msg.get_router_info().message_type != MessageType::FORWARD)
        return;
    
    send_to_fd(forward(msg).get_forward_data());
}